package com.woniuxy.school.dietary.order.config;

import com.woniuxy.school.dietary.order.websocket.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket的配置
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Autowired
    private MessageHandler messageHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        // 注册websocket组件 添加处理器和拦截器
        // websocket是websocket服务器的请求路径可以自己定义
        webSocketHandlerRegistry
                .addHandler(messageHandler, "/websocket")
                .setAllowedOrigins("*"); //允许跨域

        // 在某些低版本的浏览器中不支持websocket可以用sock-js替代
        webSocketHandlerRegistry.addHandler(messageHandler, "/sock-js")
                .setAllowedOrigins("*")
                // 开启sockJs支持
                .withSockJS();
    }
}
